package com.iot.blackip.service.impl;

import com.dc3.common.exception.AddException;
import com.iot.blackip.dto.Dc3BlackIpDto;
import com.iot.blackip.events.CacheRefreshEvent;
import com.iot.blackip.mapper.Dc3BlackIpMapper;
import com.iot.blackip.pojo.Dc3BlackIp;
import com.iot.blackip.service.BlackIpService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import javax.annotation.Resource;
import java.util.List;

/**
 * @Author 咕唧
 * @Date 2022/7/20 19:39
 * @Version 1.0
 */
@Service
public class BlackIpServiceImpl implements BlackIpService {

    private Dc3BlackIpMapper dc3BlackIpMapper;

    private ApplicationContext context;

    @Autowired
    public void setContext(ApplicationContext context) {
        this.context = context;
    }

    @Resource
    public void setDc3BlackIpMapper(Dc3BlackIpMapper dc3BlackIpMapper) {
        this.dc3BlackIpMapper = dc3BlackIpMapper;
    }

    @Override
    public void addBlackIp(Dc3BlackIpDto dc3BlackIpDto) {
        Assert.isTrue(dc3BlackIpDto.getIp().matches("([1-9]|[1-9]\\d|1\\d{2}|2[0-4]\\d|25[0-5])(\\.(\\d|[1-9]\\d|1\\d{2}|2[0-4]\\d|25[0-5])){3}"), () -> {
            throw new AddException("ip地址不正确");
        });
        //转换对象
        Dc3BlackIp dc3BlackIp = new Dc3BlackIp();
        dc3BlackIp.setIp(dc3BlackIpDto.getIp());
        dc3BlackIp.setDescription(dc3BlackIpDto.getDescription());

        dc3BlackIpMapper.addBlackIp(dc3BlackIp);
        //添加刷新缓存
        refresh();
    }

    @Override
    public List<Dc3BlackIpDto> findAllIp2Dto() {
        return dc3BlackIpMapper.findAllIp2Dto();
    }

    @Override
    public Long deleteBlackIp(String id) {
        Long aLong = dc3BlackIpMapper.deleteBlackIp(id);
        //删除完成刷新缓存
        refresh();
        return aLong;
    }

    @Override
    public void refresh() {
        context.publishEvent(new CacheRefreshEvent());
    }


}
